import 'dart:io';

import 'package:dio/dio.dart';

class RetryInterceptor extends Interceptor {
  final int maxRetries;

  RetryInterceptor({this.maxRetries = 3});

  @override
  Future<void> onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    if (_shouldRetry(err)) {
      final options = err.requestOptions;
      final retryCount = options.extra['retry_count'] as int? ?? 0;

      if (retryCount < maxRetries) {
        await Future.delayed(const Duration(seconds: 1));
        options.extra['retry_count'] = retryCount + 1;
        handler.resolve(await Dio().fetch(options));
        return;
      }
    }
    handler.next(err);
  }

  bool _shouldRetry(DioException err) {
    return err.type == DioExceptionType.connectionTimeout ||
        err.type == DioExceptionType.receiveTimeout ||
        err.type == DioExceptionType.sendTimeout ||
        err.error is SocketException;
  }
}
